package com.kuaiditu.assistant.service;

import android.content.Context;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.template.IProvider;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.kuaiditu.assistant.App;
import com.kuaiditu.assistant.event.LocationEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Eenie on 2017/9/6.
 * Email: eeniework@gmail.com
 * Des:
 */

@Route(path = LocationService.PATH)
public class LocationService implements IProvider, BDLocationListener {

    private LocationClient mLocationClient;
    public static final String PATH = "/service/location";

    private boolean isFirst = true;


    @Override
    public void init(Context context) {
        mLocationClient = ((App) context).getApplicationComponent().getLocationClient();
        mLocationClient.registerLocationListener(this);
        mLocationClient.start();




    }


    public LatLng getLatLng() {
        BDLocation location = mLocationClient.getLastKnownLocation();
        LatLng latLng;
        if (location != null && (location.getLocType() == 61 || location.getLocType() == 161 || location.getLocType() == 66)) {

            latLng = new LatLng(location.getLatitude(), location.getLongitude());
        } else {
            latLng = null;
        }
        return latLng;
    }


    public void start() {
        mLocationClient.start();
    }


    @Override
    public void onReceiveLocation(BDLocation location) {

        if (location.getLocType() == 61 || location.getLocType() == 161 || location.getLocType() == 66) {

            if (isFirst) {
                EventBus.getDefault().post(new LocationEvent());
                isFirst = false;
            }

        }


//        LogUtil.e(JSON.toJSONString(bdLocation));
    }


}
